/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 029. 排序的循环链表
 * @author: WXY
 * @create: 2022-12-26 10:37
 * @Version 1.0
 **/

public class offer_nine3_insert {
    class Node {
        public int val;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _next) {
            val = _val;
            next = _next;
        }
    };
    public Node insert(Node head, int insertVal) {
        Node insertNode = new Node(insertVal);
        if (head == null) {
            Node node = insertNode;
            node.next = node;
            return node;
        }
        if (head.next == head) {
            Node node = insertNode;
            head.next = node;
            node.next = head;
            return head;
        }
        Node findHead = head.next;
        int min  = head.val;
        int max = head.val;
        Node minNode = head;
        Node maxNode = head;
        while (findHead != head) {
            if (findHead.val < min) {
                minNode = findHead;
                min  = minNode.val;
            }
            if (findHead.val > max) {
                maxNode = findHead;
                max = maxNode.val;
            }
            findHead = findHead.next;
        }
        if (maxNode.val == maxNode.next.val) {
            maxNode = maxNode.next;
        }

        if (insertVal <= minNode.val || insertVal >= maxNode.val) {
            insertMaxMin(maxNode, insertNode);
            return head;
        }
        Node curNode = minNode;
        while (curNode.next != minNode) {
            if (curNode.val < insertVal && curNode.next.val < insertVal) {
                curNode = curNode.next;
            } else {
                insertNode.next = curNode.next;
                curNode.next = insertNode;
                break;
            }
        }

        return head;
    }

    private void insertMaxMin(Node maxNode, Node insertNode) {
        insertNode.next = maxNode.next;
        maxNode.next = insertNode;
    }
}
